<script setup>
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'

const getPdf = (title) => {
    return new Promise(resolve => {
        html2Canvas(document.querySelector('#resultsHuiZongTableId'), {
            allowTaint: false,
            useCORS: true, // allowTaint、useCORS只能够出现一个
            imageTimeout: 0,
            dpi: 300,  // 像素
            scale: 4,  // 图片大小
        }).then(function (canvas) {
            // document.body.appendChild(canvas)
            // 用于将canvas对象转换为base64位编码
            let pageData = canvas.toDataURL('image/jpeg', 1.0),
                canvasWidth = canvas.width,
                canvasHeight = canvas.height,
                concentWidth = 500,
                concentHeight = Math.round((concentWidth / canvasWidth) * canvasHeight),
                position = 72,
                pageHeight = 892,
                height = concentHeight
            console.log(height, pageHeight)
            // 新建一个new JsPDF，A3的像素大小 842*1191，A4的像素大小 592*841。这个px像素不准确，不清楚他们的像素大小来源如何
            let PDF = new JsPDF('p', 'px', 'a3')
            if (height <= pageHeight) {
                // 添加图片
                PDF.addImage(pageData, 'JPEG', 68, position, concentWidth, concentHeight)
            } else {
                while (height > 0) {
                    PDF.addImage(pageData, 'JPEG', 68, position, concentWidth, concentHeight)
                    height -= pageHeight
                    position -= pageHeight
                    if (height > 0) {
                        PDF.addPage()
                    }
                }
            }
            // 保存 pdf 文档
            PDF.save(`${title}.pdf`)
            resolve(true)
        }).catch(() => {

        }).finally(() => {
            this.pdfExporting = false;
            console.log(88888)
        })
    })
};

</script>

<template>
    <button type="primary" @click="getPdf(`PDF导出`)">导出</button>
    <!-- 要转成pdf导出的html, id为resultsHuiZongTableId-->
    <div class="student-info" id="resultsHuiZongTableId">
        <div class="student-info-item">姓名：张三</div>
        <div class="student-info-item">年龄：18</div>
        <div class="student-info-item">学校：xxx高中</div>
        <div class="student-info-item">班级：6班</div>
    </div>
</template>